package org.zty.util;


import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Map;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.filters.OrFilter;
import org.htmlparser.nodes.TagNode;
import org.htmlparser.nodes.TextNode;
import org.htmlparser.util.NodeList;


public class StringUtil {
	private static final long serialVersionUID = -1598546167187523892L;

	/**
	 * 获取子字符串 创建日期：(2002-10-27 11:04:29)
	 * 
	 * @return java.lang.String
	 * @param strSource
	 *            java.lang.String
	 * @param strStart
	 *            java.lang.String
	 * @param strEnd
	 *            java.lang.String
	 */
	public static String getSubString(String strSource, String strStart,
			String strEnd) {
		if (strSource == null || strStart == null || strEnd == null) {
			return null;
		}
		int nTmp1 = strSource.indexOf(strStart);
		if (nTmp1 < 0) {
			return null;
		}
		String strTmp = strSource.substring(nTmp1);
		int nTmp2 = strTmp.indexOf(strEnd);

		if (nTmp2 < 0) {
			return null;
		}
		return strTmp.substring(strStart.length(), nTmp2);
	}

	/**
	 * 判断字符串是否是double的数字串 创建日期：(2002-10-12 16:35:36)
	 * 
	 * @return boolean
	 * @param str
	 *            java.lang.String
	 */
	public static boolean isDouble(String str) {
		try {
			toDouble(str);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * 判断字符是否是float的数字串 创建日期：(2002-10-12 16:35:36)
	 * 
	 * @return boolean
	 * @param str
	 *            java.lang.String
	 */
	public static boolean isFloat(String str) {
		try {
			toFloat(str);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * 判断字符串是否是整型
	 * 
	 * @author smice
	 * @return boolean
	 * @param str
	 *            java.lang.String
	 */
	public boolean isInt(String str) {
		try {
			toInt(str);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * 进行字符串的替换
	 * 
	 * @param strSrc
	 * @param strOld
	 * @param strNew
	 * @return if strSrc is null return null ,else return new string
	 */
	public String replace(String strSrc, String strOld, String strNew) {
		if (strSrc == null)
			return null;

		StringBuffer sb = new StringBuffer();

		int oldlen = strOld.length();
		int pos = 0;
		int lastpos = 0;
		while (lastpos < strSrc.length()
				&& (pos = strSrc.indexOf(strOld, lastpos)) > -1) {
			sb.append(strSrc.substring(lastpos, pos));
			sb.append(strNew);
			lastpos = pos + oldlen;
		}
		if (lastpos < strSrc.length()) {
			sb.append(strSrc.substring(lastpos));
		}
		return new String(sb);
	}

	/**************************************************************
	 * 
	 * replaceReturn Return a new string that have properly converted the return
	 * symbol into <br>
	 * symbol or null. Note: this method can only use for converting pure txt
	 * file into html file. Input: String src,String returnsymbol,String pLang
	 * Output: String des
	 **************************************************************/
	public String replaceReturn(String src, String returnsymbol, String pLang) {
		int i = 0;
		String des = "";
		boolean tableflag = false, multilingualflag = false;
		if (src == null)
			return "";

		if (pLang.equals("CHN") || pLang.equals("BIG5"))
			;
		else
			multilingualflag = true;

		while ((i = src.indexOf(returnsymbol)) != -1) {
			des = des + src.substring(0, i);
			src = src.substring(i + returnsymbol.length());
			if (multilingualflag)
				des = des + "<br>";
			else if (tableflag)
				des = des + "<br>";
			else if (src.indexOf(returnsymbol) == 0) {
				des = des + "<br><br>";
				src = src.substring(returnsymbol.length());
			} else if ((src.indexOf("─") == 0) || (src.indexOf("━") == 0)
					|| (src.indexOf("┄") == 0) || (src.indexOf("┅") == 0)
					|| (src.indexOf("┈") == 0) || (src.indexOf("┉") == 0)
					|| (src.indexOf("-") == 0) || (src.indexOf("┌") == 0)
					|| (src.indexOf("－") == 0)) {
				des = des + "<br>";
				tableflag = true;
			} else if ((src.indexOf("　") == 0) || (src.indexOf(" ") == 0)
					|| (src.indexOf("") == 0)) {
				des = des + "<br>&nbsp;";
				src = src.substring(1);
			} else if (src.length() > 0) {
				if (src.charAt(0) <= 127)
					des = des + "<br>";
			}
		}
		if (src != null)
			return (des + src);
		else
			return des;
	}

	/**
	 * 此处插入方法说明。 创建日期：(2002-9-12 11:53:22) 该方式自2003年9月5日起不推荐使用
	 */
	public static Vector split(String str, String strSeparator) {
		Vector vReturn = new Vector();
		if (str == null) {
			return null;
		}

		if (strSeparator == null || strSeparator.equalsIgnoreCase("")
				|| str.indexOf(strSeparator) < 0) {
			vReturn.add(0, str);
			return vReturn;
		}

		int nTmp = strSeparator.length();
		while (str.indexOf(strSeparator) >= 0) {
			int nTmp2 = str.indexOf(strSeparator);
			vReturn.add(str.substring(0, nTmp2));

			str = str.substring(nTmp2 + nTmp);
		}

		vReturn.add(str);

		return vReturn;
	}

	/**
	 * 字符串分割：将字符串按指定的分割符分割为若干字符串。
	 * 
	 * @param str
	 *            java.lang.String 需要分割的目标字符串。如果该值为null，则返回结果也为null。
	 * @param strSeparator
	 *            java.lang.String
	 *            指定的分割符，可以是字符串。如果该值为null或""，则直接返回整个字符串。如果在目标字符串中
	 *            没有发现分割符，则返回整个字符串。如果末尾有分割符，且控制标记为false，则计算末尾的分割结
	 *            果，如“aa,bb,”以“,”进行分割处理，则共有三个分割结果。
	 * @param b
	 *            boolean
	 *            控制标记，true表示将两个分隔符之间没有内容的分隔结果忽略掉，false不做这样的处理，没有内容的分隔结果将填以""。
	 * @return Vector 将分隔的结果按次序存入，保证不存在空指针。返回结果存在null的可能，因此在使用该结果前需要判断是否为null。
	 */
	public static Vector split(String str, String strSeparator, boolean b)
			throws ZException {
		try {
			Vector vReturn = new Vector();
			// 目标字符串为null的情形
			if (str == null) {
				return null;
			}

			// 分割字符串为null或""或在目标字符串中找不到分隔符的情形
			if (strSeparator == null || strSeparator.equalsIgnoreCase("")
					|| str.indexOf(strSeparator) < 0) {
				vReturn.add(0, str);
				return vReturn;
			}

			// 获取分割符的长度
			int nTmp = strSeparator.length();
			while (str.indexOf(strSeparator) >= 0) {
				int nTmp2 = str.indexOf(strSeparator);
				// 此处能保证strTmp的返回值不会为null
				String strTmp = str.substring(0, nTmp2);
				// 如果控制标记为true，表示将分隔结果为空的忽略掉
				if (b == true) {
					if (strTmp.length() >= 1) {
						vReturn.add(strTmp);
					}
				} else {
					vReturn.add(strTmp);
				}

				// 将已经处理完毕的去掉
				str = str.substring(nTmp2 + nTmp);
			}

			// 处理最后一个分隔结果
			// 如果控制标记为true，表示将分隔结果为空的忽略掉
			if (b == true) {
				if (str.length() >= 1) {
					vReturn.add(str);
				}
			} else {
				vReturn.add(str);
			}

			return vReturn;
		} catch (Exception e) {
			throw new ZException("分割数据库时出现异常");
		}
	}

	/**
	 * 字符串转换为double 创建日期：(2002-8-27 11:16:33)
	 * 
	 * @return int
	 * @param str
	 *            java.lang.String
	 */
	public static double toDouble(String str) {
		try {
			return Double.parseDouble(str);
		} catch (Exception e) {
			return 0.0d;
		}
	}
	public static double toDouble(String str,double val)
	{
		try
		{
			return Double.parseDouble(str);
		}
		catch (Exception e)
		{
			return val;
		}
	}
	/**
	 * 此处插入方法说明。 创建日期：(2002-8-27 11:16:33)
	 * 
	 * @return int
	 * @param str
	 *            java.lang.String
	 */
	public static float toFloat(String str) {
		try {
			return Float.parseFloat(str);
		} catch (Exception e) {
			return 0.0f;
		}
	}
	/**
	 * 此处插入方法说明。
	 * 创建日期：(2002-8-27 11:16:33)
	 * @return int
	 * @param str java.lang.String
	 */
	public static float toFloat(String str,float val)
	{
		try
		{
			return Float.parseFloat(str);
		}
		catch (Exception e)
		{
			return val;
		}
	}
	/**
	 * iso8859-1转换为GBK 创建日期：(2002-8-27 11:16:33)
	 * 
	 * @return int
	 * @param str
	 *            java.lang.String
	 */
	public static String toGBK(String str) throws ZException {
		if (str == null) {
			return null;
		}
		try {
			return new String(str.getBytes("iso-8859-1"), "GBK");
		} catch (Exception e) {
			throw new ZException("转换为GBK时错误");
		}
	}

	/**
	 * 自动转码方法 创建日期：(2002-8-27 11:16:33)
	 * 
	 * @return int
	 * @param str
	 *            java.lang.String
	 */
	public static String autoEncode(String str) throws ZException {
		if (str == null) {
			return null;
		}
		try {
			// 如果是AIX平台，则转码
			if (System.getProperty("os.name").equals("AIX")) {
				return new String(str.getBytes("iso-8859-1"), "GBK");
			}
			// 否则不转码
			else {
				return str;
			}
		} catch (Exception e) {
			throw new ZException("转换为GBK时错误");
		}
	}

	/**
	 * 字符串转int 创建日期：(2002-8-27 11:16:33)
	 * 
	 * @return int
	 * @param str
	 *            java.lang.String
	 */
	public static int toInt(String str) throws ZException {
		try {
			return Integer.parseInt(str);
		} catch (Exception e) {
			throw new ZException("错误的数字格式！");
		}
	}

	/**
	 * 字符串转换为数字，并给出默认值
	 * 
	 * @param str
	 *            字符串
	 * @param def
	 *            默认值
	 * @return 当字符串转换异常时，采用默认值进行提交。
	 */
	public static int toInt(String str, int def) {
		int i = 0;
		try {
			i = Integer.parseInt(str);
		} catch (Exception e) {
			i = def;
		}
		return i;
	}

	/**
	 * 将字符串转换为整数（INT），并且判断是否在规定的长度范围以内，否则将抛出异常
	 * str：转换的目标字符串，如果不需要限制长度，可直接使用toInt(String str) nMinLength：最小长度
	 * nMaxLength：最大长度 创建日期：(2002-8-27 11:16:33)
	 * 
	 * @return int
	 * @param str
	 *            java.lang.String
	 */
	public static int toInt(String str, int nMinLength, int nMaxLength)
			throws ZException {
		if (str.length() < nMinLength) {
			throw new ZException("数字小于指定的长度" + nMinLength);
		}
		if (str.length() > nMaxLength) {
			throw new ZException("数字大于指定的长度" + nMaxLength);
		}

		return toInt(str);
	}

	/**
	 * 将输入的字符串进行编码，以得到加密后的字符串，或者解密后的明文
	 * 
	 * @param str
	 *            java.lang.String:目标字符串
	 * @param nModle
	 *            int:编码模式1:将输入的字符串进行加密处理,2:将输入的字符串进行解密处理
	 */
	public static String encrypt(String strIn, int nMode) throws ZException {
		if (strIn == null) {
			throw new ZException("目标字符串不能为null");
		}

		if (nMode != 1 && nMode != 2) {
			throw new ZException("编码模式参数无效,有效值为1或2");
		}
		String strReturn = null;

		boolean flag = false;

		// 将字符串加密
		// 加密算法:加密后的长度统一变为30位,最后两位标志原字符串的有效长度,因此解密时目标字符串最长为28位
		// 解密时必须为30位。将每个字符的编码值
		if (nMode == 1) {
			flag = true;
		}

		char[] encryptString;
		char[] outEncrypt;
		String outString;
		String item;
		int nItem;

		if (strIn.equals("")) // 如果是空串不进行操作
		{
			return "";
		}

		if (flag) // 加密
		{
			encryptString = encryptCore(flag, strIn);
			item = new String();
			outString = new String();
			for (int i = 0; i < encryptString.length; i++) {
				nItem = encryptString[i]; // 将每一个字符变成数字
				item = item.valueOf(nItem);
				if (i == 0)
					outString = item;
				else
					outString += "^" + item;
			}
		} else // 解密
		{
			int j = 1;
			String tempString = strIn;
			try {
				item = getSubItem(tempString, j, "^"); // 分隔所有以'^'分隔的字符
			} catch (ZException te) {
				throw te;
			}
			encryptString = new char[256];
			while (item != null && !item.equals("null")) {
				nItem = Integer.parseInt(item);
				encryptString[j - 1] = (char) nItem;
				item = getSubItem(tempString, ++j, "^");
			}
			if (j == 1)
				outString = null;
			else {
				String thisString = new String(encryptString, 0, --j);

				outEncrypt = encryptCore(flag, thisString);
				outString = new String(outEncrypt, 0, outEncrypt.length - 1); // 去除密钥的长度1
			}
		}
		return outString;

	}

	/**
	 * 加密和解密的核心算法。
	 * 
	 * @return <code>char[]</code> 输出加密或解密后的字符数祖
	 * @param flag
	 *            boolean 标志位，flag=true 加密；flag=false 解密
	 * @param inString
	 *            java.lang.String 输入串
	 */
	private static char[] encryptCore(boolean flag, String inString) {
		char tempString[];
		char tempChar[];
		int stringLen;
		int i, pos;
		int offset_0, offset_1, offset_2, offset_3;
		int offset_4, offset_5, offset_6, offset_7;
		int offset_8, offset_9, offset_A, offset_B, offset_C;

		GregorianCalendar cal = new GregorianCalendar();
		int rand;
		int factor;
		stringLen = inString.length();
		if (flag) {
			factor = 1;
			tempString = new char[stringLen + 1];
			rand = cal.get(Calendar.MINUTE); // 以当前的分钟数为种子
			if (rand < 30)
				rand += 30;
		} else {
			factor = -1;
			tempString = new char[stringLen];
			char subChar = inString.charAt(stringLen - 1);
			rand = subChar;
			stringLen--;
		}
		if (stringLen > rand)
			offset_0 = stringLen;
		else
			offset_0 = rand + stringLen;

		/* 加密矩阵 */
		offset_1 = factor * (offset_0 - 52);
		offset_2 = factor * (offset_0 - 33);
		offset_3 = factor * (offset_0 - 4);
		offset_4 = factor * (offset_0 - 7);
		offset_5 = factor * (offset_0 - 19);
		offset_6 = factor * (offset_0 - 21);
		offset_7 = factor * (offset_0 - 43);
		offset_8 = factor * (offset_0 - 58);
		offset_9 = factor * (offset_0 - 11);
		offset_A = factor * (offset_0 - 43);
		offset_B = factor * (offset_0 - 2);
		offset_C = factor * (offset_0 - 9);
		offset_0 = factor * (offset_0);

		tempChar = inString.toCharArray();

		for (i = 0; i < stringLen; i++) {
			pos = i % 13;

			if ((int) tempChar[i] > 256) // Java的int类型为16位的，与char进行强制类型转换时可能产生负数等不正确的情况
			// 将其限制在256的范围内
			{
				tempChar[i] = (char) ((int) tempChar[i] - 65280);
			}
			switch (pos) {
			case 0:
				tempString[i] = (char) ((int) tempChar[i] + offset_0);
				break;
			case 1:
				tempString[i] = (char) ((int) tempChar[i] + offset_1);
				break;
			case 2:
				tempString[i] = (char) ((int) tempChar[i] + offset_2);
				break;
			case 3:
				tempString[i] = (char) ((int) tempChar[i] + offset_3);
				break;
			case 4:
				tempString[i] = (char) ((int) tempChar[i] + offset_4);
				break;
			case 5:
				tempString[i] = (char) ((int) tempChar[i] + offset_5);
				break;
			case 6:
				tempString[i] = (char) ((int) tempChar[i] + offset_6);
				break;
			case 7:
				tempString[i] = (char) ((int) tempChar[i] + offset_7);
				break;
			case 8:
				tempString[i] = (char) ((int) tempChar[i] + offset_8);
				break;
			case 9:
				tempString[i] = (char) ((int) tempChar[i] + offset_9);
				break;
			case 10:
				tempString[i] = (char) ((int) tempChar[i] + offset_A);
				break;
			case 11:
				tempString[i] = (char) ((int) tempChar[i] + offset_B);
				break;
			case 12:
				tempString[i] = (char) ((int) tempChar[i] + offset_C);
				break;
			default:
				tempString[i] = (char) ((int) tempChar[i] + offset_8);
			}
			if ((int) tempChar[i] > 127) // 限制在char类型可显示的127范围内
			{
				tempChar[i] = (char) (256 - (int) tempChar[i]);
			}
		}

		if (flag) {
			tempString[i++] = (char) rand;
		}
		return tempString;

	}

	/**
	 * 获得字符串中指定分隔符分隔的指定子串
	 * 
	 * @param strItem
	 *            String 父字符串
	 * @param Index
	 *            int 第几个子串
	 * @param separator
	 *            String 分隔符
	 * 
	 * @return <code>String</code> 指定的子串，如果不存在，则返回""
	 * @exceprtion com.trs.was.WAZException 父字符串或分隔符为空
	 */
	public static String getSubItem(String strItem, int Index, String separator)
			throws ZException {
		if (strItem == null) {
			throw new ZException("XXX#父字符串为空#PTools.getSubItem#");
		}
		if (separator == null) {
			throw new ZException("XXX#分隔符为空#PTools.getSubItem#");
		}

		if (Index <= 0) {
			return "";
		}

		int pos1, pos2, i;
		String strSub;
		pos1 = pos2 = 0;
		i = 1;
		try {
			do {
				pos2 = strItem.indexOf(separator, pos1); // 找到一个分隔符
				if (i == Index) // 指定的子串
				{
					if (pos2 != -1) // 不是最后一个，pos2不为-1，从pos1到pos2中间的字符
						strSub = strItem.substring(pos1, pos2);
					else
						// 最后一个，从pos1开始以后所有的字符
						strSub = strItem.substring(pos1);
					return strSub; // 返回获得的子串
				}
				pos1 = pos2 + separator.length(); // 跳过分隔符，以便寻找下一个分隔符
				i++;
			} while (pos2 != -1);

			return null;
		} catch (Exception e) {
			throw new ZException("XXX#在获得父字符串'" + strItem + "'以'" + separator
					+ "'分隔的第'" + Index + "'个子串时出现异常#PTools.getSubItem#"
					+ e.getMessage());
		}
	}

	/**
	 * 字符串在浏览器中的显示格式处理，详细处理方式如下：
	 * <ul>
	 * <li>处理空格：将空格置换为”<code>&amp;nbsp;</code>“
	 * <li>处理换行：将文本换行标记”\n“置换为”&lt;br>\n“
	 * <li>处理HTML标签：将HTML标记第一个字符”<code><</code>“置换为”<code>&amp;lt;</code>
	 * “，这样文本中的HTML代码将以源码的 形式显示在浏览器中。
	 * </ul>
	 * 
	 * @param String
	 *            s:待处理的字符串
	 * @return String :处理完毕后的字符串
	 */
	public static String browseFormat(String s) {
		String temp = "", temp1 = "", temp2 = "", temp3 = "";
		boolean state = false, state1 = false;
		if (s == null)
			s = "";
		int i = s.length();
		char ac[] = new char[i + 1];
		s.getChars(0, i, ac, 0);
		StringBuffer stringbuffer = new StringBuffer((int) ((double) i * 2.0D));
		for (int j = 0; j < i; j++) {
			char c = ac[j];
			switch (c) {
			case 32: // ' '
				if (j == 0)
					stringbuffer.append("&nbsp;");
				else if ((ac[j - 1] >= 48) && (ac[j - 1] <= 122))
					stringbuffer.append(" ");
				else
					stringbuffer.append("&nbsp;");
				break;

			case 10: // '\n'
				stringbuffer.append("<br>\n");
				break;

			/*
			 * case 60: // '<' stringbuffer.append("&lt;"); break;
			 */

			default:
				stringbuffer.append(c);
				break;

			}
		}
		return stringbuffer.toString();
	}

	/**
	 * 字符串在浏览器中的显示格式处理，详细处理方式如下：
	 * <ul>
	 * <li>处理空格：将空格置换为”<code>&amp;nbsp;</code>“
	 * <li>处理换行：将文本换行标记”\n“置换为”&lt;br>\n“
	 * </ul>
	 * HTML标记不处理，这样HTML标记将被浏览器解释输出，这样做比较危险，页面可能会被正文中所含的
	 * HTML代码所影响，因此，除非必须，或者信任该正文内容，否则都应该过虑
	 * 
	 * @param String
	 *            s:待处理的字符串
	 * @return String :处理完毕后的字符串
	 */
	public static String htmlFormat(String s) {
		String temp = "", temp1 = "", temp2 = "", temp3 = "";
		boolean state = false, state1 = false;
		if (s == null)
			s = "";
		int i = s.length();
		char ac[] = new char[i + 1];
		s.getChars(0, i, ac, 0);
		StringBuffer stringbuffer = new StringBuffer((int) ((double) i * 2.0D));
		for (int j = 0; j < i; j++) {
			char c = ac[j];
			switch (c) {
			case 32: // ' '
				if (j == 0)
					stringbuffer.append("&nbsp;");
				else if ((ac[j - 1] >= 48) && (ac[j - 1] <= 122))
					stringbuffer.append(" ");
				else
					stringbuffer.append("&nbsp;");
				break;

			case 10: // '\n'
				stringbuffer.append("<br>\n");
				break;

			default:
				stringbuffer.append(c);
				break;

			}
		}
		return stringbuffer.toString();
	}

	/**
	 * String数组转化为int数组
	 * 
	 * @param str
	 * @return int[]
	 */
	public static int[] strArray2Int(String[] str) throws ZException {
		if (str == null || str.length == 0) {
			return null;
		}
		int len = str.length;
		int[] temp = new int[len];
		try {
			for (int i = 0; i < len; i++) {
				temp[i] = Integer.parseInt(str[i]);
			}
		} catch (Exception e) {
			throw new ZException("字符串中含有非数字字符", e);
		}
		return temp;
	}

	/**
	 * 对url进行编码处理
	 * 
	 * @param src
	 * @param enc
	 * @return
	 */
	public static String encode(String src, String enc) {
		try {
			return URLEncoder.encode(src, enc);
		} catch (Exception e) {
			new ZException("url进行编码时，发生未知异常", e);
		}
		return null;
	}

	/**
	 * 对url进行反编码
	 * 
	 * @param src
	 * @param enc
	 * @return
	 */
	public static String decode(String src, String enc) {
		try {
			return URLDecoder.decode(src, enc);
		} catch (Exception e) {
			new ZException("对url进行反编码时发生未知异常", e);
		}
		return null;
	}

	/**
	 * 去除正文中的html标签
	 * 
	 * @param src
	 * @return
	 */
	public static String htmlFilter(String html, String charset)
			throws ZException {
		if (html == null && html.length() < 0) {
			throw new ZException("文本获取内容为空");
		}
		Parser parser = null;
		NodeList nodelist = null;
		String line = "";
		StringBuffer sb = new StringBuffer();
		Node[] nodes = null;
		NodeFilter textFilter = null;

		try {
			parser = Parser.createParser(html, charset);
			textFilter = new NodeClassFilter(TextNode.class);
			OrFilter lastFilter = new OrFilter();
			lastFilter.setPredicates(new NodeFilter[] { textFilter });
			nodelist = parser.parse(textFilter);
			nodes = nodelist.toNodeArray();
			for (int i = 0; i < nodes.length; i++) {
				Node node = nodes[i];
				if (node instanceof TextNode) {
					TextNode textnode = (TextNode) node;
					line = textnode.getText();
				}
				if (line == null || line.length() <= 0)
					continue;
				if (line.length() > 0) {
					sb.append(line);
				}
			}
			nodelist.removeAll();
		} catch (Exception e) {
			new ZException("", e);
		}
		return sb.toString();
	}

	/**
	 * 去除正文中的html标签
	 * 
	 * @param src
	 * @return
	 */
	public static String htmlFilterExt(String html, String charset)
			throws ZException {
		if (html == null && html.length() < 0) {
			throw new ZException("文本获取内容为空");
		}
		Parser parser = null;
		NodeList nodelist = null;
		String line = "";
		StringBuffer sb = new StringBuffer();
		Node[] nodes = null;
		NodeFilter textFilter = null;

		try {
			parser = Parser.createParser(html, charset);
			textFilter = new NodeClassFilter(TextNode.class);
			OrFilter lastFilter = new OrFilter();
			lastFilter.setPredicates(new NodeFilter[] { textFilter });
			nodelist = parser.parse(textFilter);
			nodes = nodelist.toNodeArray();
			for (int i = 0; i < nodes.length; i++) {
				Node node = nodes[i];
				if (node instanceof TextNode) {
					TextNode textnode = (TextNode) node;
					line = textnode.getText();
				} else if (node instanceof TagNode) {
					if (((TagNode) node).getTagName().equalsIgnoreCase("br")) {
						line = node.toHtml();
					}
				}
				if (line == null || line.length() <= 0)
					continue;
				if (line.length() > 0) {
					sb.append(line);
				}
			}
			nodelist.removeAll();
		} catch (Exception e) {
			new ZException("", e);
		}
		return sb.toString();
	}

	public static String replaceStr(String _strSrc, String _strOld,
			String _strNew) {
		if (_strSrc == null)
			return null;
		char srcBuff[] = _strSrc.toCharArray();
		int nSrcLen = srcBuff.length;
		if (nSrcLen == 0)
			return "";
		char oldStrBuff[] = _strOld.toCharArray();
		int nOldStrLen = oldStrBuff.length;
		if (nOldStrLen == 0 || nOldStrLen > nSrcLen)
			return _strSrc;
		StringBuffer retBuff = new StringBuffer(nSrcLen
				* (1 + _strNew.length() / nOldStrLen));
		boolean bIsFound = false;
		for (int i = 0; i < nSrcLen;) {
			bIsFound = false;
			if (srcBuff[i] == oldStrBuff[0]) {
				int j;
				for (j = 1; j < nOldStrLen; j++)
					if (i + j >= nSrcLen || srcBuff[i + j] != oldStrBuff[j])
						break;

				bIsFound = j == nOldStrLen;
			}
			if (bIsFound) {
				retBuff.append(_strNew);
				i += nOldStrLen;
			} else {
				int nSkipTo;
				if (i + nOldStrLen >= nSrcLen)
					nSkipTo = nSrcLen - 1;
				else
					nSkipTo = i;
				for (; i <= nSkipTo; i++)
					retBuff.append(srcBuff[i]);

			}
		}

		srcBuff = (char[]) null;
		oldStrBuff = (char[]) null;
		return retBuff.toString();
	}

	/**
	 * 处理null为空字符
	 * 
	 * @param str
	 * @return if str==null return "" otherwise str
	 */
	public static String procNull(String str) {
		return str == null ? "" : str;
	}
	/**
	 * 处理空字符串，并给出默认值
	 * @param str
	 * @param def
	 * @return
	 */
	public static String procStrDefault(String src,String def){
		if(src==null||src.length()<=0){
			src = def;
		}
		return src;
	}
	/**
	 * 处理html中的:'&','<','>','"',转为html显示字符
	 * @param _sContent
	 * @return
	 */
	public static String filterForHTMLValue(String _sContent) {
		if (_sContent == null)
			return "";
		char srcBuff[] = _sContent.toCharArray();
		int nLen = srcBuff.length;
		if (nLen == 0)
			return "";
		StringBuffer retBuff = new StringBuffer((int) ((double) nLen * 1.8D));
		for (int i = 0; i < nLen; i++) {
			char cTemp = srcBuff[i];
			switch (cTemp) {
			case 38: // '&'
				if (i + 1 < nLen) {
					cTemp = srcBuff[i + 1];
					if (cTemp == '#')
						retBuff.append("&");
					else
						retBuff.append("&amp;");
				} else {
					retBuff.append("&amp;");
				}
				break;

			case 60: // '<'
				retBuff.append("&lt;");
				break;

			case 62: // '>'
				retBuff.append("&gt;");
				break;

			case 34: // '"'
				retBuff.append("&quot;");
				break;

			default:
				retBuff.append(cTemp);
				break;
			}
		}

		return retBuff.toString();
	}

	/**
	 * 生成空格字符
	 * @param _length 字符个数
	 * @return
	 */
	public static String makeBlanks(int _length) {
		if (_length < 1)
			return "";
		StringBuffer buffer = new StringBuffer(_length);
		for (int i = 0; i < _length; i++)
			buffer.append(' ');

		return buffer.toString();
	}

	/**
	 * 长整形字符串转Long，发生转换异常返回0L
	 * @param v
	 * @return
	 */
	public static Long toLong(String v) {
		return toLong(v, 0L);
	}

	/**
	 * 长整形字符串转Long，发生转换异常返回给定的默认值
	 * @param v
	 * @param defval
	 * @return
	 */
	public static Long toLong(String v, long defval) {
		try {
			return Long.parseLong(v);
		} catch (Exception e) {
			return defval;
		}
	}
	/**
	 * 进行布尔类型转换，转换失败返回false
	 * @param src
	 * @return
	 */
	public static boolean toBoolean(String src){
		try {
			return Boolean.parseBoolean(src);
		} catch (Exception e) {
			return false;
		}
	}
	/**
	 * 字符串转bool型，并给出默认值
	 * 
	 * @param str
	 *            字符串
	 * @param f
	 *            默认值
	 * @return 当发生转换异常生成默认值
	 */
	public static boolean toBool(String str, boolean f) {
		try {
			return Boolean.parseBoolean(str);
		} catch (Exception e) {
			return f;
		}
	}

	/**
	 * 按字长截断
	 * 
	 * @param str
	 *            字符
	 * @param length
	 *            字数
	 * @param end
	 *            结尾标示
	 * @return
	 */
	public static String subString(String str, int length, String end) {
		if (str.length() > length) {
			return str.substring(0, length) + end;
		}
		return str;
	}
	/**
	 * 截断字符串
	 * @param src
	 * @param len
	 * @return
	 * @throws ZException 
	 */
	public static String subString(String src,int len) throws ZException{
		//TODO:修改结束符是否进行处理
		String str="";
		try {
			int l = src.length();
			if(l>len){
				str = src.substring(0,len);
			}
			else
			{
				str = src;
			}
		} catch (Exception e) {
			throw new ZException("截断字符串失败",e);
		}
		return str;
	}
	/**
	 * 字符串替换，进行多个通配替换
	 * 
	 * @param src
	 * @param regex
	 * @param sb
	 * @param hm
	 * 
	 *            原字符串 server=#HTTP# shutdown="#SHUTDOW#" regex: #(.+?)# sb:
	 *            StringBuffer sb = new StringBuffer(); hm: HashMap hm = new
	 *            HashMap(); hm.put("HTTP","8081");hm.put("SHUTDOWN","8006");
	 *            sb= server=8081 shutdown="8006"
	 */
	public static void replaceReg(String src, String regex, StringBuffer sb,
			Map<String, String> hm) {
		Matcher m = Pattern.compile(regex).matcher(src);
		while (m.find()) {
			String key = m.group(1);
			if (hm.containsKey(key)) {
				m.appendReplacement(sb, hm.get(key));
			}
		}
		m.appendTail(sb);
	}

	/**
	 * 将一个字符串的首字母改为大写或者小写
	 * 
	 * @param srcString
	 *            源字符串
	 * @param flag
	 *            大小写标识，ture小写，false大些
	 * @return 改写后的新字符串
	 */
	public static String toLowerCaseInitial(String srcString, boolean flag) {
		StringBuilder sb = new StringBuilder();
		if (flag) {
			sb.append(Character.toLowerCase(srcString.charAt(0)));
		} else {
			sb.append(Character.toUpperCase(srcString.charAt(0)));
		}
		sb.append(srcString.substring(1));
		return sb.toString();
	}

	/**
	 * 将一个字符串按照句点（.）分隔，返回最后一段
	 * 
	 * @param clazzName
	 *            源字符串
	 * @return 句点（.）分隔后的最后一段字符串
	 */
	public static String getLastName(String clazzName) {
		String[] ls = clazzName.split("\\.");
		return ls[ls.length - 1];
	}

	/**
	 * 对象toString()方法，为null时给出默认值
	 * @param obj
	 * @param defaultStr
	 * @return
	 */
	public static String obj2Str(Object obj, String defaultStr) {
		String msg = "";
		if (obj == null) {
			msg = defaultStr;
		} else {
			msg = obj.toString();
		}
		return msg;
	}

	/**
	 * 调用toString()方法，对象为null是返回空字符
	 * @param obj
	 * @return
	 */
	public static String obj2Str(Object obj) {
		return obj2Str(obj, "");
	}

	/**
	 * 汉字转unicode
	 * 
	 * @param s
	 * @return
	 */
	public static String toUnicode(String s) {
		StringBuffer ret = new StringBuffer();
		if (s == null) {
			return null;
		}
		int maxLoop = s.length();
		for (int i = 0; i < maxLoop; i++) {
			char character = s.charAt(i);
			if (character <= '') {
				ret.append(character);
			} else {
				ret.append("\\u");
				String hexStr = Integer.toHexString(character);
				int zeroCount = 4 - hexStr.length();
				for (int j = 0; j < zeroCount; j++) {
					ret.append('0');
				}
				ret.append(hexStr);
			}
		}
		return ret.toString();
	}

	/**
	 * 将unicode编码字符串还原
	 * @param unicodeStr
	 * @return
	 */
	public static String fromUnicode(String unicodeStr) {
		if (unicodeStr == null) {
			return null;
		}
		StringBuffer retBuf = new StringBuffer();
		int maxLoop = unicodeStr.length();
		for (int i = 0; i < maxLoop; i++) {
			if (unicodeStr.charAt(i) == '\\') {
				if ((i < maxLoop - 5)
						&& ((unicodeStr.charAt(i + 1) == 'u') || (unicodeStr
								.charAt(i + 1) == 'U'))) {
					try {
						retBuf.append((char) Integer.parseInt(
								unicodeStr.substring(i + 2, i + 6), 16));

						i += 5;
					} catch (NumberFormatException e) {
						retBuf.append(unicodeStr.charAt(i));
					}
				} else
					retBuf.append(unicodeStr.charAt(i));
			} else {
				retBuf.append(unicodeStr.charAt(i));
			}
		}
		return retBuf.toString();
	}
	public static boolean isBlank(String str){
		return str==null||"".equals(str);
	}
	public static boolean isNotBlank(String str){
		return str!=null&&!"".equals(str);
	}
}

